﻿using EventBus.Abstractions;
using GraphQLSample.Domain.Core;
using GraphQLSample.Infrastructure.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace GraphQLSample.Application.DomainEventHandlers
{
    public class UserCreatedEventHandler
        : IEventHandler<UserCreatedEvent>
    {
        private readonly ApplicationContext _ctx;
        public UserCreatedEventHandler(ApplicationContext ctx)
        {
            _ctx = ctx;
        }
        public bool CanHandle(IEvent @event)
        {
            return @event.GetType() == typeof(UserCreatedEvent);
        }

        public async Task HandleAsync(UserCreatedEvent @event, CancellationToken cancellationToken = default(CancellationToken))
        {
            await _ctx.AddAsync(new User() { Name = @event.Name });
            await _ctx.SaveChangesAsync();
        }

        public async Task HandleAsync(IEvent @event, CancellationToken cancellationToken = default(CancellationToken))
        {
            var evn = @event as UserCreatedEvent;
            await _ctx.AddAsync(new User() { Name = evn.Name });
            await _ctx.SaveChangesAsync();
        }
    }
}
